package com.fm.financemanage.service;

import com.fm.financemanage.component.TokenComponent;
import com.fm.financemanage.constant.UserConstants;
import com.fm.financemanage.exception.BusinessException;
import com.fm.financemanage.mapper.AccountantMapper;
import com.fm.financemanage.mapper.UserMapper;
import com.fm.financemanage.model.po.Accountant;
import com.fm.financemanage.model.po.User;
import com.fm.financemanage.model.vo.UserInfoVo;
import com.fm.financemanage.model.vo.UserLoginVo;
import com.fm.financemanage.model.vo.UserTokenVo;
import com.fm.financemanage.utils.MessageDigestUtil;
import com.fm.financemanage.utils.TextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private AccountantMapper accountantMapper;

    @Autowired
    private TokenComponent tokenComponent;

    public UserInfoVo login(String account, String password, String companyKey) {
        UserInfoVo userLoginVo = null;
        if (TextUtil.isEmpty(companyKey)) {
            userLoginVo = userMapper.getByAccount(account);
        } else {
            userLoginVo = accountantMapper.getByAccountAndUserUuid(account, companyKey);
        }
        if (userLoginVo == null) {
            throw new BusinessException("当前账号不存在");
        }

        if (userLoginVo.getState() == 0) {
            throw new BusinessException("当前账号不可用");
        }
        if (!userLoginVo.getPassword().equals(MessageDigestUtil.encryptMD5(password.getBytes()))) {
            throw new BusinessException("密码错误");
        }
        final UserTokenVo build = UserTokenVo.builder()
                .timestamp(System.currentTimeMillis())
                .uuid(userLoginVo.getUuid())
                .companyKey(companyKey)
                .userType(TextUtil.isEmpty(companyKey)? UserConstants.USER_TYPE_DZ:UserConstants.USER_TYPE_KJ)
                .account(account).build();
        userLoginVo.setUserTokenVo(build);

        return userLoginVo;
    }
}
